package cliente.auxiliar;

import common.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author ziza
 */
public class Conexao {

    private Socket tcp_cliente = null;
    private ObjectInputStream in = null;
    private ObjectOutputStream out = null;
    int tenta=0;
    private String estado = "Desligado";
    private String host;
    private int port;
    private RMIconnectionCliente handling=null;

    public Conexao() {
    }

    public Conexao(Socket tcp_cliente, String host, int port) {
        this.tcp_cliente=tcp_cliente;
        this.host = host;
        this.port = port;
        //estado="Ligado";
        System.out.println("A ir para o in e out");
        Conexao_tcp();
    }

    public Conexao(String host, int port) {
        
        this.host = host;
        this.port = port;
        //conexao_RMI();
    }
    
    public synchronized String getEstado() {
        return estado;
    }

    public ObjectInputStream getObjectInput(){
        return in;
    }

    public ObjectOutputStream getObjectOutput(){
        return out;
    }

    public int getPort(){
        return port;
    }
 
    public String getHost(){
        return host;
    }

    public Socket getTcp_cliente() {
        return tcp_cliente;
    }

    public RMIconnectionCliente getHandling() {
        return handling;
    }

    public void setHandling(RMIconnectionCliente handling) {
        this.handling = handling;
    }

    

    public void setIn(ObjectInputStream in) {
        this.in = in;
    }

    public void setOut(ObjectOutputStream out) {
        this.out = out;
    }

    public void setTcp_cliente(Socket tcp_cliente) {
        this.tcp_cliente = tcp_cliente;
    }


    synchronized public void setEstado(String estado) {
        this.estado = estado;
    }

    public int Conexao_tcp(){

        try {
            out = new ObjectOutputStream(tcp_cliente.getOutputStream());
            in = new ObjectInputStream(tcp_cliente.getInputStream());

            System.out.println("[INFO]Ligacao estabelecida com sucesso!");
            estado = "Ligado";

            if(tenta==50){
                System.out.println("[ERRO]Tentativas gastas");
                return -1;
            }
            

        } catch (Exception ex) {
            System.out.println("[ERRO]Nao existe socket com o servidor\n"+ex.getMessage());
            estado="Desligado";
            tenta++;
            Conexao_tcp();
            try {
                Thread.sleep(30000);
            } catch (InterruptedException ex1) {
                System.out.println("[ERRO]\n"+ex1.getMessage());
                return -1;
            }
        }
        return 0;
    }


    public void sendMensagemTCP(Menssagem sms) throws IOException{
            System.out.println("Mensagem:"+ sms.getMenssagem());
            out.writeObject(sms);
            System.out.println("[INFO]Mensagem enviada!");
            out.flush();
    }


     public int conexao_RMI() {
        try {
             Registry registry = LocateRegistry.getRegistry(host, port);
             RMIconnectionCliente liga = (RMIconnectionCliente) registry.lookup("service");

            this.setHandling(liga);
            estado = "Ligado";
            System.out.println("OK!!!");           
            return 0;
        } catch (NotBoundException ex) {
            System.out.println("NotBoundExeption: "+ex.getMessage());
            return -1;
        }  catch (RemoteException ex) {
            System.out.println("RemoteExeption: "+ex.getMessage());
            return -1;
        }
    }

    public void fechaLigacoes(){
        try {
            this.out.close();
            this.in.close();
            this.tcp_cliente.close();
        } catch (IOException ex) {
            System.out.println("[Erro]:Erro ao fecher a Ligacao.");
        }
    }
    
}

